package org.dromara.oce.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.enums.FormatsType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.*;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.oce.config.DsdjConfig;
import org.dromara.oce.config.JuLiangConfig;
import org.dromara.oce.constant.ReferralLinkType;
import org.dromara.oce.domain.OceAdvertiserEverydayCost;
import org.dromara.oce.domain.OceAdvertiserReferralRelation;
import org.dromara.oce.domain.OceEverydayCostHours;
import org.dromara.oce.domain.bo.OceAdvertiserEverydayCostBo;
import org.dromara.oce.domain.dto.GetOceEverydayCostCensusDataDTO;
import org.dromara.oce.domain.dto.GetOceEverydayCostCensusDramaDataDTO;
import org.dromara.oce.domain.dto.GetOceEverydayCostCensusPitcherDataDTO;
import org.dromara.oce.domain.req.IaaOrderAmountHoursDTO;
import org.dromara.oce.domain.req.OrderAmountHoursDTO;
import org.dromara.oce.domain.req.UpdateAdvertiserHoursAmountReq;
import org.dromara.oce.domain.req.UpdateIaaAdvertiserHoursAmountReq;
import org.dromara.oce.domain.vo.OceAdvertiserEverydayCostVo;
import org.dromara.oce.mapper.OceAdvertiserEverydayCostMapper;
import org.dromara.oce.mapper.OceEverydayCostHoursMapper;
import org.dromara.oce.service.AuditorService;
import org.dromara.oce.service.OceAdvertiserEverydayCostService;
import org.dromara.oce.service.OceAdvertiserReferralRelationService;
import org.dromara.oce.service.OceEverydayCostHoursService;
import org.dromara.oce.utils.CommonConstants;
import org.dromara.oce.utils.DateTimeUtil;
import org.dromara.oce.utils.TimeUtils;
import org.dromara.system.domain.SysDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 广告主消耗记录Service业务层处理
 *
 * @author Lion Li
 * @date 2024-12-24
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class OceAdvertiserEverydayCostServiceImpl extends ServiceImpl<OceAdvertiserEverydayCostMapper, OceAdvertiserEverydayCost> implements OceAdvertiserEverydayCostService {

    private final OceAdvertiserEverydayCostMapper baseMapper;
    private final SysDeptMapper deptMapper;
    private final OceEverydayCostHoursService oceEverydayCostHoursService;
    private final OceEverydayCostHoursMapper oceEverydayCostHoursMapper;
    private final OceAdvertiserReferralRelationService oceAdvertiserReferralRelationService;
    private final ScheduledExecutorService scheduledExecutorService;
    private final DsdjConfig dsdjConfig;
    private final JuLiangConfig juLiangConfig;
    private final AuditorService auditorService;

    /**
     * 查询广告主消耗记录
     *
     * @param advertiserCostId 主键
     * @return 广告主消耗记录
     */
    @Override
    public OceAdvertiserEverydayCostVo queryById(Long advertiserCostId) {
        return baseMapper.selectVoById(advertiserCostId);
    }

    /**
     * 查询符合条件的广告主总消耗数据
     *
     * @param bo 查询条件
     * @return 广告主总消耗数据
     */
    @Override
    public GetOceEverydayCostCensusDataDTO sumCost(OceAdvertiserEverydayCostBo bo) {
        GetOceEverydayCostCensusDataDTO totalDto = new GetOceEverydayCostCensusDataDTO();
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = buildQueryWrapper(bo);
        List<OceAdvertiserEverydayCost> list = baseMapper.selectList(lqw);
        if (CollectionUtils.isNotEmpty(list)) {
            // 总消耗
            BigDecimal cost = list.stream().map(OceAdvertiserEverydayCost::getCost).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日总收入
            BigDecimal thatdayTotalAmount = list.stream().map(OceAdvertiserEverydayCost::getThatdayTotalAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日总收入
            BigDecimal thatdayRegisterTotalAmount = list.stream().map(OceAdvertiserEverydayCost::getThatdayRegisterTotalAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日总支付笔数
            Integer thatdayPaidTotalNum = list.stream().map(OceAdvertiserEverydayCost::getThatdayPaidTotalNum).filter(Objects::nonNull).reduce(0, Integer::sum);
            // 当日分成金额
            BigDecimal thatdayDividendAmount = list.stream().map(OceAdvertiserEverydayCost::getThatdayDividendAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日注册用户的分成金额
            BigDecimal thatdayRegisterDividendAmount = list.stream().map(OceAdvertiserEverydayCost::getThatdayRegisterDividendAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日利润金额=当日分成金额-当日消耗
            BigDecimal thatdayProfitAmount = list.stream().map(OceAdvertiserEverydayCost::getThatdayProfitAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 消耗时速
            BigDecimal costHoursSpeed = list.stream().map(OceAdvertiserEverydayCost::getCostHoursSpeed).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日IAA总收入
            BigDecimal iaaTotalAmount = list.stream().map(OceAdvertiserEverydayCost::getIaaTotalAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日IAA分成金额
            BigDecimal iaaDividendAmount = list.stream().map(OceAdvertiserEverydayCost::getIaaDividendAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日注册用户的IAA总收入
            BigDecimal iaaRegisterTotalAmount = list.stream().map(OceAdvertiserEverydayCost::getIaaRegisterTotalAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日注册用户的IAA分成金额
            BigDecimal iaaRegisterDividendAmount = list.stream().map(OceAdvertiserEverydayCost::getIaaRegisterDividendAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日LTV
            BigDecimal attributionMicroGame0dLtv = list.stream().map(OceAdvertiserEverydayCost::getAttributionMicroGame0dLtv).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            // 当日广告变现ROI
            BigDecimal attributionMicroGame0dRoi = NumberUtil.equals(cost, BigDecimal.ZERO) ? BigDecimal.ZERO : attributionMicroGame0dLtv.divide(cost, 2, RoundingMode.HALF_UP);
            // 当日注册用户的利润金额
            BigDecimal thatdayRegisterProfitAmount = list.stream().map(OceAdvertiserEverydayCost::getThatdayRegisterProfitAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);

            //商务当日分成金额
            BigDecimal thatdayDividendAmountSw = list.stream().map(OceAdvertiserEverydayCost::getThatdayDividendAmountSw).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            //商务当日IAA分成金额
            BigDecimal iaaDividendAmountSw = list.stream().map(OceAdvertiserEverydayCost::getIaaDividendAmountSw).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            //商务当日利润金额
            BigDecimal thatdayProfitAmountSw = list.stream().map(OceAdvertiserEverydayCost::getThatdayProfitAmountSw).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);


            // 回本率
            BigDecimal extRecoveryRate = BigDecimal.ZERO;
            // 新增回本率
            BigDecimal extRegisterRecoveryRate = BigDecimal.ZERO;
            BigDecimal costTemp = cost;
            if (NumberUtil.equals(cost, BigDecimal.ZERO)) {
                costTemp = new BigDecimal("1");
            } else {
//                costTemp = costTemp.divide(new BigDecimal("1.015"), 4, RoundingMode.HALF_UP);
            }
            if (CommonConstants.IAA_FLAG_NO.equals(bo.getIaaFlag())) {
                extRecoveryRate = thatdayTotalAmount.divide(costTemp, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            } else {
                extRecoveryRate = (iaaTotalAmount.add(thatdayTotalAmount)).divide(costTemp, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            }
            if (CommonConstants.IAA_FLAG_NO.equals(bo.getIaaFlag())) {
                extRegisterRecoveryRate = thatdayRegisterTotalAmount.divide(costTemp, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            } else {
                extRegisterRecoveryRate = (iaaRegisterTotalAmount.add(thatdayRegisterTotalAmount)).divide(costTemp, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP);
            }
            totalDto.setCost(cost);
            totalDto.setThatdayTotalAmount(thatdayTotalAmount);
            totalDto.setThatdayRegisterTotalAmount(thatdayRegisterTotalAmount);
            totalDto.setThatdayPaidTotalNum(thatdayPaidTotalNum);
            totalDto.setThatdayDividendAmount(thatdayDividendAmount);
            totalDto.setThatdayRegisterDividendAmount(thatdayRegisterDividendAmount);
            totalDto.setThatdayProfitAmount(thatdayProfitAmount);
            totalDto.setThatdayRegisterProfitAmount(thatdayRegisterProfitAmount);
            totalDto.setCostHoursSpeed(costHoursSpeed);
            totalDto.setIaaTotalAmount(iaaTotalAmount);
            totalDto.setIaaDividendAmount(iaaDividendAmount);
            totalDto.setIaaRegisterTotalAmount(iaaRegisterTotalAmount);
            totalDto.setIaaRegisterDividendAmount(iaaRegisterDividendAmount);
            totalDto.setExtRecoveryRate(extRecoveryRate);
            totalDto.setExtRegisterRecoveryRate(extRegisterRecoveryRate);
            totalDto.setAttributionMicroGame0dLtv(attributionMicroGame0dLtv);
            totalDto.setAttributionMicroGame0dRoi(attributionMicroGame0dRoi);
            totalDto.setThatdayDividendAmountSw(thatdayDividendAmountSw);
            totalDto.setIaaDividendAmountSw(iaaDividendAmountSw);
            totalDto.setThatdayProfitAmountSw(thatdayProfitAmountSw);

        }
        return totalDto;
    }

    /**
     * 分页查询投手数据列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 投手数据分页列表
     */
    @Override
    public TableDataInfo<GetOceEverydayCostCensusPitcherDataDTO> queryPitcherPageList(OceAdvertiserEverydayCostBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = buildQueryWrapper(bo);
        if (StringUtils.isNotBlank(bo.getCreateName())) {
            lqw.groupBy(OceAdvertiserEverydayCost::getThatdayTimestamp);
        } else {
            lqw.groupBy(OceAdvertiserEverydayCost::getCreateName);
        }
        if (StringUtils.equals("convert", pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("");
            if (StringUtils.equals("asc", pageQuery.getIsAsc())) {
                lqw.orderByAsc(OceAdvertiserEverydayCost::getConvert);
            } else {
                lqw.orderByDesc(OceAdvertiserEverydayCost::getConvert);
            }
        } else if (StringUtils.equals("show", pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("");
            if (StringUtils.equals("asc", pageQuery.getIsAsc())) {
                lqw.orderByAsc(OceAdvertiserEverydayCost::getShow);
            } else {
                lqw.orderByDesc(OceAdvertiserEverydayCost::getShow);
            }
        }
        Page<GetOceEverydayCostCensusPitcherDataDTO> result = baseMapper.getPitcherPageList(pageQuery.build(), lqw);
        List<GetOceEverydayCostCensusPitcherDataDTO> dtos = result.getRecords();
        if (CollectionUtils.isNotEmpty(dtos)) {
            for (GetOceEverydayCostCensusPitcherDataDTO dto : dtos) {
                dto.setIaaDividendAmount(dto.getIaaDividendAmount());
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询投手数据列表
     *
     * @param bo 查询条件
     * @return 投手数据列表
     */
    @Override
    public List<GetOceEverydayCostCensusPitcherDataDTO> queryPitcherList(OceAdvertiserEverydayCostBo bo) {
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = buildQueryWrapper(bo);
        lqw.groupBy(OceAdvertiserEverydayCost::getCreateName);
        List<GetOceEverydayCostCensusPitcherDataDTO> dtos = baseMapper.getPitcherPageList(lqw);
        if (CollectionUtils.isNotEmpty(dtos)) {
            for (GetOceEverydayCostCensusPitcherDataDTO dto : dtos) {
                dto.setIaaDividendAmount(dto.getIaaDividendAmount());
            }
        }
        return dtos;
    }

    /**
     * 分页查询短剧数据列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 短剧数据记录分页列表
     */
    @Override
    public TableDataInfo<GetOceEverydayCostCensusDramaDataDTO> queryDramaPageList(OceAdvertiserEverydayCostBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = buildQueryWrapper(bo);
        lqw.groupBy(OceAdvertiserEverydayCost::getDramaTitle);
        if (StringUtils.equals("convert", pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("");
            if (StringUtils.equals("asc", pageQuery.getIsAsc())) {
                lqw.orderByAsc(OceAdvertiserEverydayCost::getConvert);
            } else {
                lqw.orderByDesc(OceAdvertiserEverydayCost::getConvert);
            }
        } else if (StringUtils.equals("show", pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("");
            if (StringUtils.equals("asc", pageQuery.getIsAsc())) {
                lqw.orderByAsc(OceAdvertiserEverydayCost::getShow);
            } else {
                lqw.orderByDesc(OceAdvertiserEverydayCost::getShow);
            }
        }
        Page<GetOceEverydayCostCensusDramaDataDTO> result = baseMapper.getDramaPageList(pageQuery.build(), lqw);
        List<GetOceEverydayCostCensusDramaDataDTO> list = result.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            for (GetOceEverydayCostCensusDramaDataDTO dto : list) {
                dto.setRecoveryRate();
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询短剧数据列表
     *
     * @param bo 查询条件
     * @return 短剧数据记录列表
     */
    @Override
    public List<GetOceEverydayCostCensusDramaDataDTO> queryDramaList(OceAdvertiserEverydayCostBo bo) {
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = buildQueryWrapper(bo);
        lqw.groupBy(OceAdvertiserEverydayCost::getDramaTitle);
        return baseMapper.getDramaPageList(lqw);
    }

    /**
     * 分页查询广告主消耗记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 广告主消耗记录分页列表
     */
    @Override
    public TableDataInfo<OceAdvertiserEverydayCostVo> queryPageList(OceAdvertiserEverydayCostBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = buildQueryWrapper(bo);
        lqw.and((wrapper) -> {
            wrapper.gt(OceAdvertiserEverydayCost::getCost, 0)
                .or().gt(OceAdvertiserEverydayCost::getThatdayTotalAmount, 0)
                .or().gt(OceAdvertiserEverydayCost::getIaaTotalAmount, 0);
        });
        if (StringUtils.equals("convert", pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("");
            if (StringUtils.equals("asc", pageQuery.getIsAsc())) {
                lqw.orderByAsc(OceAdvertiserEverydayCost::getConvert);
            } else {
                lqw.orderByDesc(OceAdvertiserEverydayCost::getConvert);
            }
        } else if (StringUtils.equals("show", pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("");
            if (StringUtils.equals("asc", pageQuery.getIsAsc())) {
                lqw.orderByAsc(OceAdvertiserEverydayCost::getShow);
            } else {
                lqw.orderByDesc(OceAdvertiserEverydayCost::getShow);
            }
        }
        Page<OceAdvertiserEverydayCostVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的广告主消耗记录列表
     *
     * @param bo 查询条件
     * @return 广告主消耗记录列表
     */
    @Override
    public List<OceAdvertiserEverydayCostVo> queryList(OceAdvertiserEverydayCostBo bo) {
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = buildQueryWrapper(bo);
        lqw.and((wrapper) -> {
            wrapper.gt(OceAdvertiserEverydayCost::getCost, 0)
                .or().gt(OceAdvertiserEverydayCost::getThatdayTotalAmount, 0)
                .or().gt(OceAdvertiserEverydayCost::getIaaTotalAmount, 0);
        });
        return baseMapper.selectVoList(lqw);
    }

    public LambdaQueryWrapper<OceAdvertiserEverydayCost> buildQueryWrapper(OceAdvertiserEverydayCostBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OceAdvertiserEverydayCost> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getReferralLinkId() != null, OceAdvertiserEverydayCost::getReferralLinkId, bo.getReferralLinkId());
        lqw.eq(bo.getReferralLinkType() != null, OceAdvertiserEverydayCost::getReferralLinkType, bo.getReferralLinkType());
        lqw.eq(StringUtils.isNotBlank(bo.getThirdAdvertiserAppCode()), OceAdvertiserEverydayCost::getThirdAdvertiserAppCode, bo.getThirdAdvertiserAppCode());
        lqw.eq(StringUtils.isNotBlank(bo.getThirdAdvertiserId()), OceAdvertiserEverydayCost::getThirdAdvertiserId, bo.getThirdAdvertiserId());
        lqw.like(StringUtils.isNotBlank(bo.getThirdAdvertiserName()), OceAdvertiserEverydayCost::getThirdAdvertiserName, bo.getThirdAdvertiserName());
        lqw.eq(bo.getThatdayTimestamp() != null, OceAdvertiserEverydayCost::getThatdayTimestamp, bo.getThatdayTimestamp());
        lqw.eq(StringUtils.isNotBlank(bo.getThatdayDate()), OceAdvertiserEverydayCost::getThatdayDate, bo.getThatdayDate());
        lqw.eq(bo.getThatdayTotalAmount() != null, OceAdvertiserEverydayCost::getThatdayTotalAmount, bo.getThatdayTotalAmount());
        lqw.eq(bo.getThatdayDividendAmount() != null, OceAdvertiserEverydayCost::getThatdayDividendAmount, bo.getThatdayDividendAmount());
        lqw.eq(bo.getThatdayProfitAmount() != null, OceAdvertiserEverydayCost::getThatdayProfitAmount, bo.getThatdayProfitAmount());
        lqw.eq(bo.getThatdayPaidTotalNum() != null, OceAdvertiserEverydayCost::getThatdayPaidTotalNum, bo.getThatdayPaidTotalNum());
        lqw.eq(bo.getThatdayPaidUseNum() != null, OceAdvertiserEverydayCost::getThatdayPaidUseNum, bo.getThatdayPaidUseNum());
        lqw.eq(bo.getThatdayRegisterTotalAmount() != null, OceAdvertiserEverydayCost::getThatdayRegisterTotalAmount, bo.getThatdayRegisterTotalAmount());
        lqw.eq(bo.getThatdayRegisterDividendAmount() != null, OceAdvertiserEverydayCost::getThatdayRegisterDividendAmount, bo.getThatdayRegisterDividendAmount());
        lqw.eq(bo.getIaaTotalAmount() != null, OceAdvertiserEverydayCost::getIaaTotalAmount, bo.getIaaTotalAmount());
        lqw.eq(bo.getIaaDividendAmount() != null, OceAdvertiserEverydayCost::getIaaDividendAmount, bo.getIaaDividendAmount());
        lqw.eq(bo.getIaaRegisterTotalAmount() != null, OceAdvertiserEverydayCost::getIaaRegisterTotalAmount, bo.getIaaRegisterTotalAmount());
        lqw.eq(bo.getIaaRegisterDividendAmount() != null, OceAdvertiserEverydayCost::getIaaRegisterDividendAmount, bo.getIaaRegisterDividendAmount());
        lqw.like(StringUtils.isNotBlank(bo.getDramaTitle()), OceAdvertiserEverydayCost::getDramaTitle, bo.getDramaTitle());
        lqw.eq(bo.getCost() != null, OceAdvertiserEverydayCost::getCost, bo.getCost());
        lqw.eq(bo.getShow() != null, OceAdvertiserEverydayCost::getShow, bo.getShow());
        lqw.eq(bo.getAvgShowCost() != null, OceAdvertiserEverydayCost::getAvgShowCost, bo.getAvgShowCost());
        lqw.eq(bo.getClick() != null, OceAdvertiserEverydayCost::getClick, bo.getClick());
        lqw.eq(bo.getAvgClickCost() != null, OceAdvertiserEverydayCost::getAvgClickCost, bo.getAvgClickCost());
        lqw.eq(bo.getCtr() != null, OceAdvertiserEverydayCost::getCtr, bo.getCtr());
        lqw.eq(bo.getConvert() != null, OceAdvertiserEverydayCost::getConvert, bo.getConvert());
        lqw.eq(bo.getConvertCost() != null, OceAdvertiserEverydayCost::getConvertCost, bo.getConvertCost());
        lqw.eq(bo.getConvertRate() != null, OceAdvertiserEverydayCost::getConvertRate, bo.getConvertRate());
        lqw.eq(bo.getActive() != null, OceAdvertiserEverydayCost::getActive, bo.getActive());
        lqw.eq(bo.getActiveCost() != null, OceAdvertiserEverydayCost::getActiveCost, bo.getActiveCost());
        lqw.eq(bo.getActiveRate() != null, OceAdvertiserEverydayCost::getActiveRate, bo.getActiveRate());
        lqw.eq(bo.getActivePay() != null, OceAdvertiserEverydayCost::getActivePay, bo.getActivePay());
        lqw.eq(bo.getActivePayCost() != null, OceAdvertiserEverydayCost::getActivePayCost, bo.getActivePayCost());
        lqw.eq(bo.getActivePayRate() != null, OceAdvertiserEverydayCost::getActivePayRate, bo.getActivePayRate());
        lqw.eq(bo.getGamePayCount() != null, OceAdvertiserEverydayCost::getGamePayCount, bo.getGamePayCount());
        lqw.eq(bo.getGamePayCost() != null, OceAdvertiserEverydayCost::getGamePayCost, bo.getGamePayCost());
        lqw.eq(bo.getCostHoursSpeed() != null, OceAdvertiserEverydayCost::getCostHoursSpeed, bo.getCostHoursSpeed());
        lqw.like(StringUtils.isNotBlank(bo.getCreateName()), OceAdvertiserEverydayCost::getCreateName, bo.getCreateName());
        lqw.eq(bo.getAppType() != null, OceAdvertiserEverydayCost::getAppType, bo.getAppType());
        if (bo.getDeptId() != null) {
            List<SysDept> deptList = deptMapper.selectListByParentId(bo.getDeptId());
            List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
            ids.add(bo.getDeptId());
            lqw.in(OceAdvertiserEverydayCost::getDeptId, ids);
        }
        if (Objects.nonNull(bo.getIaaFlag())) {
            if (bo.getIaaFlag().equals(CommonConstants.IAA_FLAG_NO)) {
                if (!ObjectUtils.isEmpty(bo.getReferralLinkType()) && (bo.getReferralLinkType() <= CommonConstants.REFERRAL_LINK_TYPE_DIANZHONG || CommonConstants.REFERRAL_LINK_TYPE_DOUYIN_ACCOUNT_IAP == bo.getReferralLinkType())) {
                    lqw.eq(OceAdvertiserEverydayCost::getReferralLinkType, bo.getReferralLinkType());
                } else {
                    lqw.in(OceAdvertiserEverydayCost::getReferralLinkType,ReferralLinkType.REFERRAL_LINK_TYPE_SELF.getType(),ReferralLinkType.REFERRAL_LINK_TYPE_FANQIE.getType(), ReferralLinkType.REFERRAL_LINK_TYPE_DIANZHONG.getType(),ReferralLinkType.REFERRAL_LINK_TYPE_DOUYIN_ACCOUNT_IAP.getType());
                }
            } else {
                if (!ObjectUtils.isEmpty(bo.getReferralLinkType()) && (bo.getReferralLinkType() >= CommonConstants.REFERRAL_LINK_TYPE_FANQIE_IAA ||
                    CommonConstants.REFERRAL_LINK_TYPE_DOUYIN_ACCOUNT_IAA==bo.getReferralLinkType()) || CommonConstants.REFERRAL_LINK_TYPE_CHUAN_SHAN_JIA_IAA == bo.getReferralLinkType()) {
                    lqw.eq(OceAdvertiserEverydayCost::getReferralLinkType, bo.getReferralLinkType());
                } else {
                    lqw.in(OceAdvertiserEverydayCost::getReferralLinkType, ReferralLinkType.REFERRAL_LINK_TYPE_FANQIE_IAA.getType(),
                        ReferralLinkType.REFERRAL_LINK_TYPE_DAISHU_IAA.getType(),ReferralLinkType.REFERRAL_LINK_TYPE_DOUYIN_ACCOUNT_IAA.getType(),ReferralLinkType.REFERRAL_LINK_TYPE_CHUAN_SHAN_JIA_IAA.getType());
                }
            }
        }
        if (StringUtils.isNotBlank(bo.getStartDate()) && StringUtils.isNotBlank(bo.getEndDate())) {
            lqw.ge(OceAdvertiserEverydayCost::getThatdayTimestamp, TimeUtils.getTimestampSecond(bo.getStartDate()));
            lqw.le(OceAdvertiserEverydayCost::getThatdayTimestamp, TimeUtils.getTimestampSecond(bo.getEndDate()));
        }
        return lqw;
    }

    /**
     * 新增广告主消耗记录
     *
     * @param bo 广告主消耗记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OceAdvertiserEverydayCostBo bo) {
        OceAdvertiserEverydayCost add = MapstructUtils.convert(bo, OceAdvertiserEverydayCost.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setAdvertiserCostId(add.getAdvertiserCostId());
        }
        return flag;
    }

    /**
     * 修改广告主消耗记录
     *
     * @param bo 广告主消耗记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceAdvertiserEverydayCostBo bo) {
        OceAdvertiserEverydayCost update = MapstructUtils.convert(bo, OceAdvertiserEverydayCost.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceAdvertiserEverydayCost entity) {
    }

    /**
     * 校验并批量删除广告主消耗记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * referralLinkId 推广链接id(不传就是全量更新,传值就是更新那一条)
     * 校正充值
     */
    @Override
    public Boolean syncOrder(Long referralLinkId, String strDate, Boolean iaaFlag) {
        String updateDateStr = juLiangConfig.getSystemParam("oce.update.date");
        if(!ObjectUtils.isEmpty(updateDateStr)){
            updateDateStr = "2025-05-12";
        }
        try {
            Date date = DateUtils.parseDate(strDate, FormatsType.YYYY_MM_DD.getTimeFormat());
            Date updateDate = DateUtils.parseDate(updateDateStr, FormatsType.YYYY_MM_DD.getTimeFormat());
            if (date.toInstant().isBefore(updateDate.toInstant())) {
                throw new ServiceException("不能校正已经封存的订单数据");
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("referralLinkId", referralLinkId);
        params.put("strDate", strDate);
        if (!iaaFlag) {
            String url = dsdjConfig.getDsdjServerReqeustUrl() + "/system/inner/correctOrderPayTotalAmount";
            String postResult = HttpUtil.post(url, JsonUtils.toJsonString(params));
            JSONObject jsonObject = new JSONObject(postResult);
            int code = jsonObject.getInt("code", 0);
            if (code == 200) {
                List<UpdateAdvertiserHoursAmountReq> list = jsonObject.getBeanList("data", UpdateAdvertiserHoursAmountReq.class);
                for (UpdateAdvertiserHoursAmountReq req : list) {
                    correctAdvertiserOrderAmount(req);
                }
            }
            return true;
        }
        String url = dsdjConfig.getDsdjServerReqeustUrl() + "/system/inner/correctIaaTotalAmount";
        String postResult = HttpUtil.post(url, JsonUtils.toJsonString(params));
        JSONObject jsonObject = new JSONObject(postResult);
        int code = jsonObject.getInt("code", 0);
        if (code == 200) {
            List<UpdateIaaAdvertiserHoursAmountReq> list = jsonObject.getBeanList("data", UpdateIaaAdvertiserHoursAmountReq.class);
            for (UpdateIaaAdvertiserHoursAmountReq iaaReq : list) {
                correctAdvertiserIaaOrderAmount(iaaReq);
            }
        }
        return true;
    }


    @Override
    public Long updateAdvertiserOrderAmount(UpdateAdvertiserHoursAmountReq req) {
        //查询推广链接跟广告主关系，然后计算分成金额
        OceAdvertiserReferralRelation relation = oceAdvertiserReferralRelationService.getCacheAdvertiserInfoByReferralLinkId(req.getReferralLinkId());
        if (relation == null) {
            log.warn("推广链接绑定的广告主未找到，推广链接id：{}，跳过保存", req.getReferralLinkId());
            // 消息推送
            auditorService.sendMessage(1896813718528081921L, "推广链接" + req.getReferralLinkId() + "绑定的广告主未找到,请及时检查");
            return null;
        }
        Integer appType = relation.getAppType();
        Integer referralLinkType = relation.getReferralLinkType();
        OrderAmountHoursDTO dateDTO = null;

        List<OceAdvertiserEverydayCost> everydayCostList = new ArrayList<>();
        Map<Long, OrderAmountHoursDTO> dateMap = req.getDateMap();
        for (Map.Entry<Long, OrderAmountHoursDTO> dateEntry : dateMap.entrySet()) {
            if (!relation.isDzReferralLinkType()) {
                if (relation.isFqReferralLinkType()) {
                    BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    BigDecimal iosDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getIosThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    dateEntry.getValue().setThatdayDividendAmount(dividendAmount.add(iosDividendAmount));

                    BigDecimal registerDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    BigDecimal iosRegisterDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getIosThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    dateEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount.add(iosRegisterDividendAmount));

                    dateEntry.getValue().setThatdayDividendAmountSw(dividendAmount.add(iosDividendAmount));
                    dateEntry.getValue().setThatdayRegisterDividendAmountSw(registerDividendAmount.add(iosRegisterDividendAmount));

                    dateEntry.getValue().setThatdayTotalAmount(dateEntry.getValue().getThatdayTotalAmount().add(dateEntry.getValue().getIosThatdayTotalAmount()));
                    dateEntry.getValue().setThatdayRegisterTotalAmount(dateEntry.getValue().getThatdayRegisterTotalAmount().add(dateEntry.getValue().getIosThatdayRegisterTotalAmount()));
                } else {
                    BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeDividendAmount(referralLinkType, appType, dateEntry.getValue().getThatdayTotalAmount());
                    BigDecimal registerDividendAmount = OceAdvertiserEverydayCost.computeDividendAmount(referralLinkType, appType, dateEntry.getValue().getThatdayRegisterTotalAmount());
                    dateEntry.getValue().setThatdayDividendAmount(dividendAmount);
                    dateEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount);

                    BigDecimal dividendAmountSw = OceAdvertiserEverydayCost.computeDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getThatdayTotalAmount());
                    BigDecimal registerDividendAmountSw = OceAdvertiserEverydayCost.computeDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getThatdayRegisterTotalAmount());
                    dateEntry.getValue().setThatdayDividendAmountSw(dividendAmountSw);
                    dateEntry.getValue().setThatdayRegisterDividendAmountSw(registerDividendAmountSw);
                }
            }

            dateDTO = dateEntry.getValue();
            OceAdvertiserEverydayCost everydayCost = this.getOne(new LambdaQueryWrapper<OceAdvertiserEverydayCost>().eq(OceAdvertiserEverydayCost::getReferralLinkId, req.getReferralLinkId())
                .eq(OceAdvertiserEverydayCost::getThatdayTimestamp, dateDTO.getThatdayTimestamp()).last("limit 1"));
            boolean isAdd = false;
            if (everydayCost == null) {
                isAdd = true;
                everydayCost = new OceAdvertiserEverydayCost();
                BeanUtil.copyProperties(relation, everydayCost);
                everydayCost.setThatdayTimestamp(dateDTO.getThatdayTimestamp());
                everydayCost.setThatdayDate(DateTimeUtil.getStrDate(dateDTO.getThatdayTimestamp()));
            }
            everydayCost.setThatdayTotalAmount(everydayCost.getThatdayTotalAmount().add(dateDTO.getThatdayTotalAmount()));
            everydayCost.setThatdayDividendAmount(everydayCost.getThatdayDividendAmount().add(dateDTO.getThatdayDividendAmount()));
            everydayCost.setThatdayPaidTotalNum(everydayCost.getThatdayPaidTotalNum() + dateDTO.getThatdayPaidTotalNum());
            everydayCost.setThatdayPaidUseNum(everydayCost.getThatdayPaidUseNum() + dateDTO.getThatdayPaidUseNum());
            everydayCost.setThatdayRegisterTotalAmount(everydayCost.getThatdayRegisterTotalAmount().add(dateDTO.getThatdayRegisterTotalAmount()));
            everydayCost.setThatdayRegisterDividendAmount(everydayCost.getThatdayRegisterDividendAmount().add(dateDTO.getThatdayRegisterDividendAmount()));

            everydayCost.setThatdayDividendAmountSw(everydayCost.getThatdayDividendAmountSw().add(dateDTO.getThatdayDividendAmountSw()));
            everydayCost.setThatdayRegisterDividendAmountSw(everydayCost.getThatdayRegisterDividendAmountSw().add(dateDTO.getThatdayRegisterDividendAmountSw()));

            everydayCost.computeProfitAmount();
            everydayCost.computeRateValue();

            if (isAdd) {
                this.save(everydayCost);
            } else {
                this.updateById(everydayCost);
            }
            everydayCostList.add(everydayCost);

            OrderAmountHoursDTO finalDateDTO = dateDTO;
            scheduledExecutorService.schedule(() -> {
                oceEverydayCostHoursService.syncOceCostData(List.of(relation), DateTimeUtil.getStrDate(finalDateDTO.getThatdayTimestamp()), finalDateDTO.getThatdayTimestamp());
            }, 2, TimeUnit.SECONDS);
        }

        List<OceEverydayCostHours> addHoursList = new ArrayList<>();
        List<OceEverydayCostHours> updateHoursList = new ArrayList<>();

        Set<Long> dateList = req.getHoursMap().values().stream().map(OrderAmountHoursDTO::getThatdayTimestamp).collect(Collectors.toSet());
        List<OceEverydayCostHours> hoursList = oceEverydayCostHoursMapper.selectJobList(new LambdaQueryWrapper<OceEverydayCostHours>().eq(OceEverydayCostHours::getReferralLinkId, req.getReferralLinkId())
            .in(OceEverydayCostHours::getThatdayTimestamp, dateList).orderByAsc(OceEverydayCostHours::getThatdayHoursTimestamp));

        Map<Long, OrderAmountHoursDTO> hoursMap = req.getHoursMap();
        for (Map.Entry<Long, OrderAmountHoursDTO> hoursEntry : hoursMap.entrySet()) {
            if (!relation.isDzReferralLinkType()) {
                if (relation.isFqReferralLinkType()) {
                    BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    BigDecimal iosDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    hoursEntry.getValue().setThatdayDividendAmount(dividendAmount.add(iosDividendAmount));
                    hoursEntry.getValue().setThatdayDividendAmountSw(dividendAmount.add(iosDividendAmount));

                    BigDecimal registerDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    BigDecimal iosRegisterDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    hoursEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount.add(iosRegisterDividendAmount));
                    hoursEntry.getValue().setThatdayRegisterDividendAmountSw(registerDividendAmount.add(iosRegisterDividendAmount));

                    hoursEntry.getValue().setThatdayTotalAmount(hoursEntry.getValue().getThatdayTotalAmount().add(hoursEntry.getValue().getIosThatdayTotalAmount()));
                    hoursEntry.getValue().setThatdayRegisterTotalAmount(hoursEntry.getValue().getThatdayRegisterTotalAmount().add(hoursEntry.getValue().getIosThatdayRegisterTotalAmount()));

                    hoursEntry.getValue().setDividendAmountHoursCurrent(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursCurrent(), CommonConstants.DEVICE_PLATFORM_ANDROID).add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursCurrent(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursOne(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursOne(), CommonConstants.DEVICE_PLATFORM_ANDROID).add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursOne(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursTwo(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursTwo(), CommonConstants.DEVICE_PLATFORM_ANDROID).add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursTwo(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursThree(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursThree(), CommonConstants.DEVICE_PLATFORM_ANDROID).add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursThree(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursFour(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursFour(), CommonConstants.DEVICE_PLATFORM_ANDROID).add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursFour(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursFive(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursFive(), CommonConstants.DEVICE_PLATFORM_ANDROID).add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursFive(), CommonConstants.DEVICE_PLATFORM_IOS)));
                } else {
                    BigDecimal dividendAmount = OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getThatdayTotalAmount());
                    BigDecimal registerDividendAmount = OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getThatdayRegisterTotalAmount());
                    hoursEntry.getValue().setThatdayDividendAmount(dividendAmount);
                    hoursEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount);

                    BigDecimal dividendAmountSw = OceAdvertiserEverydayCost.computeDividendAmountSw(referralLinkType, appType, hoursEntry.getValue().getThatdayTotalAmount());
                    BigDecimal registerDividendAmountSw = OceAdvertiserEverydayCost.computeDividendAmountSw(referralLinkType, appType, hoursEntry.getValue().getThatdayRegisterTotalAmount());
                    hoursEntry.getValue().setThatdayDividendAmountSw(dividendAmountSw);
                    hoursEntry.getValue().setThatdayRegisterDividendAmountSw(registerDividendAmountSw);

                    hoursEntry.getValue().setDividendAmountHoursCurrent(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursCurrent()));
                    hoursEntry.getValue().setDividendAmountHoursOne(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursOne()));
                    hoursEntry.getValue().setDividendAmountHoursTwo(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursTwo()));
                    hoursEntry.getValue().setDividendAmountHoursThree(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursThree()));
                    hoursEntry.getValue().setDividendAmountHoursFour(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFour()));
                    hoursEntry.getValue().setDividendAmountHoursFive(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFive()));
                }
            }

            OrderAmountHoursDTO hoursDTO = hoursEntry.getValue();
            if (hoursDTO.getThatdayTimestamp().longValue() != DateTimeUtil.getBeginTimestampSecond().longValue()) {
                log.info("时速日期时间戳不等于当天日期时间戳，则将当日注册收入金额、当日注册收入分成金额，加到那一天对应数据");
                Optional<OceAdvertiserEverydayCost> first = everydayCostList.stream().filter(item -> item.getThatdayTimestamp().longValue() == hoursDTO.getThatdayTimestamp().longValue()).findFirst();
                OceAdvertiserEverydayCost everydayCost = null;
                if (first.isPresent() && first.get() != null) {
                    everydayCost = first.get();
                } else {
                    everydayCost = this.getOne(new LambdaQueryWrapper<OceAdvertiserEverydayCost>().eq(OceAdvertiserEverydayCost::getReferralLinkId, req.getReferralLinkId())
                        .eq(OceAdvertiserEverydayCost::getThatdayTimestamp, hoursDTO.getThatdayTimestamp()).last("limit 1"));
                    if (everydayCost != null) {
                        everydayCostList.add(everydayCost);
                    }
                }
                if (everydayCost != null) {
                    everydayCost.setThatdayPaidUseNum(everydayCost.getThatdayPaidUseNum() + hoursDTO.getThatdayPaidUseNum());
                    everydayCost.setThatdayPaidTotalNum(everydayCost.getThatdayPaidTotalNum() + hoursDTO.getThatdayPaidTotalNum());
                    everydayCost.setThatdayRegisterTotalAmount(everydayCost.getThatdayRegisterTotalAmount().add(hoursDTO.getThatdayRegisterTotalAmount()));
                    everydayCost.setThatdayRegisterDividendAmount(everydayCost.getThatdayRegisterDividendAmount().add(hoursDTO.getThatdayRegisterDividendAmount()));
                    everydayCost.setThatdayRegisterDividendAmountSw(everydayCost.getThatdayRegisterDividendAmountSw().add(hoursDTO.getThatdayRegisterDividendAmountSw()));
                    everydayCost.computeProfitAmount();
                    everydayCost.computeRateValue();
                    this.updateById(everydayCost);
                }

            }

            Optional<OceEverydayCostHours> first = hoursList.stream().filter(item -> item.getThatdayTimestamp().longValue() == hoursDTO.getThatdayTimestamp().longValue()
                && item.getThatdayHoursTimestamp().longValue() == hoursDTO.getThatdayHoursTimestamp().longValue()).findFirst();
            boolean isHoursAdd = false;
            OceEverydayCostHours hoursCost = null;
            if (first.isEmpty()) {
                isHoursAdd = true;
                hoursCost = new OceEverydayCostHours();
                BeanUtil.copyProperties(relation, hoursCost);
                hoursCost.setThatdayTimestamp(hoursDTO.getThatdayTimestamp());
                hoursCost.setThatdayDate(DateTimeUtil.getStrDate(hoursDTO.getThatdayTimestamp()));
                hoursCost.setThatdayHoursTimestamp(hoursDTO.getThatdayHoursTimestamp());
                hoursCost.setThatdayHoursDate(TimeUtils.getStrHoursDate(hoursDTO.getThatdayHoursTimestamp()));
            } else {
                hoursCost = first.get();
            }

            hoursCost.setThatdayTotalAmount(hoursCost.getThatdayTotalAmount().add(hoursDTO.getThatdayTotalAmount()));
            hoursCost.setThatdayRegisterTotalAmount(hoursCost.getThatdayRegisterTotalAmount().add(hoursDTO.getThatdayRegisterTotalAmount()));
            hoursCost.setThatdayDividendAmount(hoursCost.getThatdayDividendAmount().add(hoursDTO.getThatdayDividendAmount()));
            hoursCost.setThatdayRegisterDividendAmount(hoursCost.getThatdayRegisterDividendAmount().add(hoursDTO.getThatdayRegisterDividendAmount()));
            hoursCost.setThatdayPaidTotalNum(hoursCost.getThatdayPaidTotalNum() + hoursDTO.getThatdayPaidTotalNum());
            hoursCost.setThatdayPaidUseNum(hoursCost.getThatdayPaidUseNum() + hoursDTO.getThatdayPaidUseNum());

            hoursCost.setDividendAmountHoursCurrent(hoursCost.getDividendAmountHoursCurrent().add(hoursDTO.getDividendAmountHoursCurrent()));
            hoursCost.setDividendAmountHoursOne(hoursCost.getDividendAmountHoursOne().add(hoursDTO.getDividendAmountHoursOne()));
            hoursCost.setDividendAmountHoursTwo(hoursCost.getDividendAmountHoursTwo().add(hoursDTO.getDividendAmountHoursTwo()));
            hoursCost.setDividendAmountHoursThree(hoursCost.getDividendAmountHoursThree().add(hoursDTO.getDividendAmountHoursThree()));
            hoursCost.setDividendAmountHoursFour(hoursCost.getDividendAmountHoursFour().add(hoursDTO.getDividendAmountHoursFour()));
            hoursCost.setDividendAmountHoursFive(hoursCost.getDividendAmountHoursFive().add(hoursDTO.getDividendAmountHoursFive()));

            hoursCost.computeProfitAmount();
            hoursCost.computeRateValue();
            if (isHoursAdd) {
                addHoursList.add(hoursCost);
            } else {
                updateHoursList.add(hoursCost);
            }
        }
        oceEverydayCostHoursService.saveBatch(addHoursList);
        oceEverydayCostHoursService.updateBatchById(updateHoursList);

        return req.getReferralLinkId();
    }

    @Override
    public Long updateAdvertiserIaaOrderAmount(UpdateIaaAdvertiserHoursAmountReq iaaReq) {
        //查询推广链接跟广告主关系，然后计算分成金额
        OceAdvertiserReferralRelation relation = oceAdvertiserReferralRelationService.getCacheAdvertiserInfoByReferralLinkId(iaaReq.getReferralLinkId());
        if (relation == null) {
            log.warn("推广链接绑定的广告主未找到，推广链接id：{}，跳过保存", iaaReq.getReferralLinkId());
            // 消息推送
            auditorService.sendMessage(1896813718528081921L, "Iaa推广链接" + iaaReq.getReferralLinkId() + "绑定的广告主未找到,请及时检查");
            return null;
        }
        Integer appType = relation.getAppType();
        Integer referralLinkType = relation.getReferralLinkType();
        IaaOrderAmountHoursDTO dateDTO = null;


        List<OceAdvertiserEverydayCost> everydayCostList = new ArrayList<>();
        Map<Long, IaaOrderAmountHoursDTO> dateMap = iaaReq.getDateMap();
        for (Map.Entry<Long, IaaOrderAmountHoursDTO> dateEntry : dateMap.entrySet()) {
            BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeIaaDividendAmount(referralLinkType, appType, dateEntry.getValue().getIaaTotalAmount());
            BigDecimal iaaRegisterDividendAmount = OceAdvertiserEverydayCost.computeIaaDividendAmount(referralLinkType, appType, dateEntry.getValue().getIaaRegisterTotalAmount());
            dateEntry.getValue().setIaaDividendAmount(dividendAmount);
            dateEntry.getValue().setIaaRegisterDividendAmount(iaaRegisterDividendAmount);

            BigDecimal dividendAmountSw = OceAdvertiserEverydayCost.computeIaaDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getIaaTotalAmount());
            BigDecimal iaaRegisterDividendAmountSw = OceAdvertiserEverydayCost.computeIaaDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getIaaRegisterTotalAmount());
            dateEntry.getValue().setIaaDividendAmountSw(dividendAmountSw);
            dateEntry.getValue().setIaaRegisterDividendAmountSw(iaaRegisterDividendAmountSw);

            dateDTO = dateEntry.getValue();
            //更新收入金额
            OceAdvertiserEverydayCost everydayCost = this.getOne(new LambdaQueryWrapper<OceAdvertiserEverydayCost>().eq(OceAdvertiserEverydayCost::getReferralLinkId, iaaReq.getReferralLinkId())
                .eq(OceAdvertiserEverydayCost::getThatdayTimestamp, dateDTO.getThatdayTimestamp()).last("limit 1"));
            boolean isAdd = false;
            if (everydayCost == null) {
                isAdd = true;
                everydayCost = new OceAdvertiserEverydayCost();
                BeanUtil.copyProperties(relation, everydayCost);
                everydayCost.setThatdayTimestamp(dateDTO.getThatdayTimestamp());
                everydayCost.setThatdayDate(DateTimeUtil.getStrDate(dateDTO.getThatdayTimestamp()));
            }
            everydayCost.setIaaTotalAmount(everydayCost.getIaaTotalAmount().add(dateDTO.getIaaTotalAmount()));
            everydayCost.setIaaDividendAmount(everydayCost.getIaaDividendAmount().add(dateDTO.getIaaDividendAmount()));
            everydayCost.setIaaRegisterTotalAmount(everydayCost.getIaaRegisterTotalAmount().add(dateDTO.getIaaRegisterTotalAmount()));
            everydayCost.setIaaRegisterDividendAmount(everydayCost.getIaaRegisterDividendAmount().add(dateDTO.getIaaRegisterDividendAmount()));

            everydayCost.setIaaDividendAmountSw(everydayCost.getIaaDividendAmountSw().add(dateDTO.getIaaDividendAmountSw()));
            everydayCost.setIaaRegisterDividendAmountSw(everydayCost.getIaaRegisterDividendAmountSw().add(dateDTO.getIaaRegisterDividendAmountSw()));

            everydayCost.computeProfitAmount();
            everydayCost.computeRateValue();
            if (isAdd) {
                this.save(everydayCost);
            } else {
                this.updateById(everydayCost);
            }
            everydayCostList.add(everydayCost);

            IaaOrderAmountHoursDTO finalDateDTO = dateDTO;
            scheduledExecutorService.schedule(() -> {
                oceEverydayCostHoursService.syncOceCostData(List.of(relation), DateTimeUtil.getStrDate(finalDateDTO.getThatdayTimestamp()), finalDateDTO.getThatdayTimestamp());
            }, 2, TimeUnit.SECONDS);
        }

        List<OceEverydayCostHours> addHoursList = new ArrayList<>();
        List<OceEverydayCostHours> updateHoursList = new ArrayList<>();

        Set<Long> dateList = iaaReq.getHoursMap().values().stream().map(IaaOrderAmountHoursDTO::getThatdayTimestamp).collect(Collectors.toSet());
        List<OceEverydayCostHours> hoursList = oceEverydayCostHoursMapper.selectJobList(new LambdaQueryWrapper<OceEverydayCostHours>().eq(OceEverydayCostHours::getReferralLinkId, iaaReq.getReferralLinkId())
            .in(OceEverydayCostHours::getThatdayTimestamp, dateList).orderByAsc(OceEverydayCostHours::getThatdayHoursTimestamp));

        for (Map.Entry<Long, IaaOrderAmountHoursDTO> hoursEntry : iaaReq.getHoursMap().entrySet()) {
            BigDecimal dividendAmount = OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getIaaTotalAmount());
            BigDecimal iaaDividendAmount = OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getIaaRegisterTotalAmount());
            hoursEntry.getValue().setIaaDividendAmount(dividendAmount);
            hoursEntry.getValue().setIaaRegisterDividendAmount(iaaDividendAmount);

            BigDecimal dividendAmountSw = OceEverydayCostHours.computeIaaDividendAmountSw(referralLinkType, appType, hoursEntry.getValue().getIaaTotalAmount());
            BigDecimal iaaDividendAmountSw = OceEverydayCostHours.computeIaaDividendAmountSw(referralLinkType, appType, hoursEntry.getValue().getIaaRegisterTotalAmount());
            hoursEntry.getValue().setIaaDividendAmountSw(dividendAmountSw);
            hoursEntry.getValue().setIaaRegisterDividendAmountSw(iaaDividendAmountSw);

            hoursEntry.getValue().setDividendAmountHoursCurrent(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursCurrent()));
            hoursEntry.getValue().setDividendAmountHoursOne(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursOne()));
            hoursEntry.getValue().setDividendAmountHoursTwo(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursTwo()));
            hoursEntry.getValue().setDividendAmountHoursThree(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursThree()));
            hoursEntry.getValue().setDividendAmountHoursFour(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFour()));
            hoursEntry.getValue().setDividendAmountHoursFive(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFive()));

            IaaOrderAmountHoursDTO hoursDTO = hoursEntry.getValue();

            if (hoursDTO.getThatdayTimestamp().longValue() != DateTimeUtil.getBeginTimestampSecond().longValue()) {
                log.info("IAA时速日期时间戳不等于当天日期时间戳，则将当日注册收入金额、当日注册收入分成金额，加到那一天对应数据");
                Optional<OceAdvertiserEverydayCost> first = everydayCostList.stream().filter(item -> item.getThatdayTimestamp().longValue() == hoursDTO.getThatdayTimestamp().longValue()).findFirst();
                OceAdvertiserEverydayCost everydayCost = null;
                if (first.isPresent() && first.get() != null) {
                    everydayCost = first.get();
                } else {
                    everydayCost = this.getOne(new LambdaQueryWrapper<OceAdvertiserEverydayCost>().eq(OceAdvertiserEverydayCost::getReferralLinkId, iaaReq.getReferralLinkId())
                        .eq(OceAdvertiserEverydayCost::getThatdayTimestamp, hoursDTO.getThatdayTimestamp()).last("limit 1"));
                    if (everydayCost != null) {
                        everydayCostList.add(everydayCost);
                    }
                }
                if (everydayCost != null) {
                    everydayCost.setIaaRegisterTotalAmount(everydayCost.getIaaRegisterTotalAmount().add(hoursDTO.getIaaRegisterTotalAmount()));
                    everydayCost.setIaaRegisterDividendAmount(everydayCost.getIaaRegisterDividendAmount().add(hoursDTO.getIaaRegisterDividendAmount()));
                    everydayCost.setIaaRegisterDividendAmountSw(everydayCost.getIaaRegisterDividendAmountSw().add(hoursDTO.getIaaRegisterDividendAmountSw()));
                    everydayCost.computeProfitAmount();
                    everydayCost.computeRateValue();
                    this.updateById(everydayCost);
                }
            }

            Optional<OceEverydayCostHours> first = hoursList.stream().filter(item -> item.getThatdayTimestamp().longValue() == hoursDTO.getThatdayTimestamp().longValue()
                && item.getThatdayHoursTimestamp().longValue() == hoursDTO.getThatdayHoursTimestamp().longValue()).findFirst();
            boolean isHoursAdd = false;
            OceEverydayCostHours hoursCost = null;
            if (first.isEmpty()) {
                isHoursAdd = true;
                hoursCost = new OceEverydayCostHours();
                BeanUtil.copyProperties(relation, hoursCost);
                hoursCost.setThatdayTimestamp(hoursDTO.getThatdayTimestamp());
                hoursCost.setThatdayDate(DateTimeUtil.getStrDate(hoursDTO.getThatdayTimestamp()));
                hoursCost.setThatdayHoursTimestamp(hoursDTO.getThatdayHoursTimestamp());
                hoursCost.setThatdayHoursDate(TimeUtils.getStrHoursDate(hoursDTO.getThatdayHoursTimestamp()));
            } else {
                hoursCost = first.get();
            }
            hoursCost.setIaaTotalAmount(hoursCost.getIaaTotalAmount().add(hoursDTO.getIaaTotalAmount()));
            hoursCost.setIaaDividendAmount(hoursCost.getIaaDividendAmount().add(hoursDTO.getIaaDividendAmount()));
            hoursCost.setIaaRegisterTotalAmount(hoursCost.getIaaRegisterTotalAmount().add(hoursDTO.getIaaRegisterTotalAmount()));
            hoursCost.setIaaRegisterDividendAmount(hoursCost.getIaaRegisterDividendAmount().add(hoursDTO.getIaaRegisterDividendAmount()));
            hoursCost.computeProfitAmount();
            hoursCost.computeRateValue();

            hoursCost.setDividendAmountHoursCurrent(hoursCost.getDividendAmountHoursCurrent().add(hoursDTO.getDividendAmountHoursCurrent()));
            hoursCost.setDividendAmountHoursOne(hoursCost.getDividendAmountHoursOne().add(hoursDTO.getAmountHoursOne()));
            hoursCost.setDividendAmountHoursTwo(hoursCost.getDividendAmountHoursTwo().add(hoursDTO.getAmountHoursTwo()));
            hoursCost.setDividendAmountHoursThree(hoursCost.getDividendAmountHoursThree().add(hoursDTO.getAmountHoursThree()));
            hoursCost.setDividendAmountHoursFour(hoursCost.getDividendAmountHoursFour().add(hoursDTO.getAmountHoursFour()));
            hoursCost.setDividendAmountHoursFive(hoursCost.getDividendAmountHoursFive().add(hoursDTO.getAmountHoursFive()));

            if (isHoursAdd) {
                addHoursList.add(hoursCost);
            } else {
                updateHoursList.add(hoursCost);
            }
        }
        oceEverydayCostHoursService.saveBatch(addHoursList);
        oceEverydayCostHoursService.updateBatchById(updateHoursList);

        return iaaReq.getReferralLinkId();
    }

    @Override
    public Long correctAdvertiserOrderAmount(UpdateAdvertiserHoursAmountReq req) {
        OceAdvertiserReferralRelation relation = oceAdvertiserReferralRelationService.getCacheAdvertiserInfoByReferralLinkId(req.getReferralLinkId());
        if (relation == null) {
            log.info("推广链接绑定的广告主未找到，推广链接id：{}，跳过保存", req.getReferralLinkId(), req.getDateMap().get(req.getReferralLinkId()));
            return null;
        }

        Integer appType = relation.getAppType();
        Integer referralLinkType = relation.getReferralLinkType();

        Map<Long, OrderAmountHoursDTO> dateMap = req.getDateMap();
        OrderAmountHoursDTO dateDTO = null;
        for (Map.Entry<Long, OrderAmountHoursDTO> dateEntry : dateMap.entrySet()) {
            if (!relation.isDzReferralLinkType()) {
                if (relation.isFqReferralLinkType()) {
                    BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    BigDecimal iosDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getIosThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    dateEntry.getValue().setThatdayDividendAmount(dividendAmount.add(iosDividendAmount));
                    dateEntry.getValue().setThatdayDividendAmountSw(dividendAmount.add(iosDividendAmount));

                    BigDecimal registerDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    BigDecimal iosRegisterDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, dateEntry.getValue().getIosThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    dateEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount.add(iosRegisterDividendAmount));
                    dateEntry.getValue().setThatdayRegisterDividendAmountSw(registerDividendAmount.add(iosRegisterDividendAmount));

                    dateEntry.getValue().setThatdayTotalAmount(dateEntry.getValue().getThatdayTotalAmount().add(dateEntry.getValue().getIosThatdayTotalAmount()));
                    dateEntry.getValue().setThatdayRegisterTotalAmount(dateEntry.getValue().getThatdayRegisterTotalAmount().add(dateEntry.getValue().getIosThatdayRegisterTotalAmount()));
                } else {
                    BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeDividendAmount(referralLinkType, appType, dateEntry.getValue().getThatdayTotalAmount());
                    BigDecimal registerDividendAmount = OceAdvertiserEverydayCost.computeDividendAmount(referralLinkType, appType, dateEntry.getValue().getThatdayRegisterTotalAmount());
                    dateEntry.getValue().setThatdayDividendAmount(dividendAmount);
                    dateEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount);

                    BigDecimal dividendAmountSw = OceAdvertiserEverydayCost.computeDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getThatdayTotalAmount());
                    BigDecimal registerDividendAmountSw = OceAdvertiserEverydayCost.computeDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getThatdayRegisterTotalAmount());
                    dateEntry.getValue().setThatdayDividendAmountSw(dividendAmountSw);
                    dateEntry.getValue().setThatdayRegisterDividendAmountSw(registerDividendAmountSw);
                }
            }

            dateDTO = dateEntry.getValue();
            OceAdvertiserEverydayCost everydayCost = this.getOne(new LambdaQueryWrapper<OceAdvertiserEverydayCost>().eq(OceAdvertiserEverydayCost::getReferralLinkId, req.getReferralLinkId())
                .eq(OceAdvertiserEverydayCost::getThatdayTimestamp, dateDTO.getThatdayTimestamp()).last("limit 1"));
            boolean isAdd = false;
            if (everydayCost == null) {
                isAdd = true;
                everydayCost = new OceAdvertiserEverydayCost();
                BeanUtil.copyProperties(relation, everydayCost);
                everydayCost.setThatdayTimestamp(dateDTO.getThatdayTimestamp());
                everydayCost.setThatdayDate(DateTimeUtil.getStrDate(dateDTO.getThatdayTimestamp()));
            }

            everydayCost.setThatdayTotalAmount(dateDTO.getThatdayTotalAmount());
            everydayCost.setThatdayRegisterTotalAmount(dateDTO.getThatdayRegisterTotalAmount());
            everydayCost.setThatdayDividendAmount(dateDTO.getThatdayDividendAmount());
            everydayCost.setThatdayDividendAmountSw(dateDTO.getThatdayDividendAmountSw());
            everydayCost.setThatdayPaidTotalNum(dateDTO.getThatdayPaidTotalNum());
            everydayCost.setThatdayPaidUseNum(dateDTO.getThatdayPaidUseNum());
            everydayCost.setThatdayRegisterDividendAmount(dateDTO.getThatdayRegisterDividendAmount());
            everydayCost.setThatdayRegisterDividendAmountSw(dateDTO.getThatdayRegisterDividendAmountSw());
            everydayCost.computeProfitAmount();
            everydayCost.computeRateValue();

            if (isAdd) {
                this.save(everydayCost);
            } else {
                this.updateById(everydayCost);
            }
        }

        List<OceEverydayCostHours> addHoursList = new ArrayList<>();
        List<OceEverydayCostHours> updateHoursList = new ArrayList<>();
        List<OceEverydayCostHours> hoursList = oceEverydayCostHoursMapper.selectJobList(new LambdaQueryWrapper<OceEverydayCostHours>().eq(OceEverydayCostHours::getReferralLinkId, req.getReferralLinkId())
            .eq(OceEverydayCostHours::getThatdayTimestamp, dateDTO.getThatdayTimestamp()));

        Map<Long, OrderAmountHoursDTO> hoursMap = req.getHoursMap();
        for (Map.Entry<Long, OrderAmountHoursDTO> hoursEntry : hoursMap.entrySet()) {
            if (!relation.isDzReferralLinkType()) {
                if (relation.isFqReferralLinkType()) {
                    BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    BigDecimal iosDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosThatdayTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    hoursEntry.getValue().setThatdayDividendAmount(dividendAmount.add(iosDividendAmount));

                    BigDecimal registerDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_IOS);
                    BigDecimal iosRegisterDividendAmount = OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosThatdayRegisterTotalAmount(), CommonConstants.DEVICE_PLATFORM_ANDROID);
                    hoursEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount.add(iosRegisterDividendAmount));

                    //计算分成后，在加入总的
                    hoursEntry.getValue().setThatdayTotalAmount(hoursEntry.getValue().getThatdayTotalAmount().add(hoursEntry.getValue().getIosThatdayTotalAmount()));
                    hoursEntry.getValue().setThatdayRegisterTotalAmount(hoursEntry.getValue().getThatdayRegisterTotalAmount().add(hoursEntry.getValue().getIosThatdayRegisterTotalAmount()));

                    hoursEntry.getValue().setDividendAmountHoursCurrent(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursCurrent(), CommonConstants.DEVICE_PLATFORM_ANDROID)
                        .add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursCurrent(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursOne(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursOne(), CommonConstants.DEVICE_PLATFORM_ANDROID)
                        .add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursOne(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursTwo(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursTwo(), CommonConstants.DEVICE_PLATFORM_ANDROID)
                        .add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursTwo(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursThree(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursThree(), CommonConstants.DEVICE_PLATFORM_ANDROID)
                        .add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursThree(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursFour(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursFour(), CommonConstants.DEVICE_PLATFORM_ANDROID)
                        .add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursFour(), CommonConstants.DEVICE_PLATFORM_IOS)));
                    hoursEntry.getValue().setDividendAmountHoursFive(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getAmountHoursFive(), CommonConstants.DEVICE_PLATFORM_ANDROID)
                        .add(OceAdvertiserEverydayCost.computeFqDividendAmount(appType, hoursEntry.getValue().getIosAmountHoursFive(), CommonConstants.DEVICE_PLATFORM_IOS)));
                } else {
                    BigDecimal dividendAmount = OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getThatdayTotalAmount());
                    hoursEntry.getValue().setThatdayDividendAmount(dividendAmount);
                    BigDecimal registerDividendAmount = OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getThatdayRegisterTotalAmount());
                    hoursEntry.getValue().setThatdayRegisterDividendAmount(registerDividendAmount);

                    hoursEntry.getValue().setDividendAmountHoursCurrent(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursCurrent()));
                    hoursEntry.getValue().setDividendAmountHoursOne(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursOne()));
                    hoursEntry.getValue().setDividendAmountHoursTwo(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursTwo()));
                    hoursEntry.getValue().setDividendAmountHoursThree(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursThree()));
                    hoursEntry.getValue().setDividendAmountHoursFour(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFour()));
                    hoursEntry.getValue().setDividendAmountHoursFive(OceEverydayCostHours.computeDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFive()));
                }
            }

            OrderAmountHoursDTO hoursDTO = hoursEntry.getValue();

            OceEverydayCostHours hoursCost = null;
            Optional<OceEverydayCostHours> first = hoursList.stream().filter(item -> item.getThatdayHoursTimestamp().longValue() == hoursDTO.getThatdayHoursTimestamp().longValue()).findFirst();
            boolean isHoursAdd = false;
            if (first.isEmpty()) {
                isHoursAdd = true;
                hoursCost = new OceEverydayCostHours();
                BeanUtil.copyProperties(relation, hoursCost);
                hoursCost.setThatdayTimestamp(hoursDTO.getThatdayTimestamp());
                hoursCost.setThatdayDate(DateTimeUtil.getStrDate(hoursDTO.getThatdayTimestamp()));
                hoursCost.setThatdayHoursTimestamp(hoursDTO.getThatdayHoursTimestamp());
                hoursCost.setThatdayHoursDate(TimeUtils.getStrHoursDate(hoursDTO.getThatdayHoursTimestamp()));
            } else {
                hoursCost = first.get();
            }

            hoursCost.setThatdayTotalAmount(hoursDTO.getThatdayTotalAmount());
            hoursCost.setThatdayRegisterTotalAmount(hoursDTO.getThatdayRegisterTotalAmount());
            hoursCost.setThatdayDividendAmount(hoursDTO.getThatdayDividendAmount());
            hoursCost.setThatdayPaidTotalNum(hoursDTO.getThatdayPaidTotalNum());
            hoursCost.setThatdayPaidUseNum(hoursDTO.getThatdayPaidUseNum());
            hoursCost.setThatdayRegisterDividendAmount(hoursDTO.getThatdayRegisterDividendAmount());

            hoursCost.setDividendAmountHoursCurrent(hoursDTO.getDividendAmountHoursCurrent());
            hoursCost.setDividendAmountHoursOne(hoursDTO.getDividendAmountHoursOne());
            hoursCost.setDividendAmountHoursTwo(hoursDTO.getDividendAmountHoursTwo());
            hoursCost.setDividendAmountHoursThree(hoursDTO.getDividendAmountHoursThree());
            hoursCost.setDividendAmountHoursFour(hoursDTO.getDividendAmountHoursFour());
            hoursCost.setDividendAmountHoursFive(hoursDTO.getDividendAmountHoursFive());

            hoursCost.computeProfitAmount();
            hoursCost.computeRateValue();
            if (isHoursAdd) {
                addHoursList.add(hoursCost);
            } else {
                updateHoursList.add(hoursCost);
            }
        }
        oceEverydayCostHoursService.saveBatch(addHoursList);
        oceEverydayCostHoursService.updateBatchById(updateHoursList);

        return req.getReferralLinkId();
    }


    @Override
    public Long correctAdvertiserIaaOrderAmount(UpdateIaaAdvertiserHoursAmountReq iaaReq) {
        OceAdvertiserReferralRelation relation = oceAdvertiserReferralRelationService.getCacheAdvertiserInfoByReferralLinkId(iaaReq.getReferralLinkId());
        if (relation == null) {
            log.info("推广链接绑定的广告主未找到，推广链接id：{}，跳过保存", iaaReq.getReferralLinkId(), iaaReq.getDateMap().get(iaaReq.getReferralLinkId()));
            return null;
        }
        Integer appType = relation.getAppType();
        Integer referralLinkType = relation.getReferralLinkType();
        IaaOrderAmountHoursDTO dateDTO = null;

        Map<Long, IaaOrderAmountHoursDTO> dateMap = iaaReq.getDateMap();
        for (Map.Entry<Long, IaaOrderAmountHoursDTO> dateEntry : dateMap.entrySet()) {
            BigDecimal dividendAmount = OceAdvertiserEverydayCost.computeIaaDividendAmount(referralLinkType, appType, dateEntry.getValue().getIaaTotalAmount());
            dateEntry.getValue().setIaaDividendAmount(dividendAmount);
            BigDecimal iaaRegisterDividendAmount = OceAdvertiserEverydayCost.computeIaaDividendAmount(referralLinkType, appType, dateEntry.getValue().getIaaRegisterTotalAmount());
            dateEntry.getValue().setIaaRegisterDividendAmount(iaaRegisterDividendAmount);

            BigDecimal dividendAmountSw = OceAdvertiserEverydayCost.computeIaaDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getIaaTotalAmount());
            dateEntry.getValue().setIaaDividendAmountSw(dividendAmountSw);
            BigDecimal iaaRegisterDividendAmountSw = OceAdvertiserEverydayCost.computeIaaDividendAmountSw(referralLinkType, appType, dateEntry.getValue().getIaaRegisterTotalAmount());
            dateEntry.getValue().setIaaRegisterDividendAmountSw(iaaRegisterDividendAmountSw);

            dateDTO = dateEntry.getValue();
            //更新收入金额
            OceAdvertiserEverydayCost everydayCost = this.getOne(new LambdaQueryWrapper<OceAdvertiserEverydayCost>().eq(OceAdvertiserEverydayCost::getReferralLinkId, iaaReq.getReferralLinkId())
                .eq(OceAdvertiserEverydayCost::getThatdayTimestamp, dateDTO.getThatdayTimestamp()).last("limit 1"));
            boolean isAdd = false;
            if (everydayCost == null) {
                isAdd = true;
                everydayCost = new OceAdvertiserEverydayCost();
                BeanUtil.copyProperties(relation, everydayCost);
                everydayCost.setThatdayTimestamp(dateDTO.getThatdayTimestamp());
                everydayCost.setThatdayDate(DateTimeUtil.getStrDate(dateDTO.getThatdayTimestamp()));
            }
            everydayCost.setIaaTotalAmount(dateDTO.getIaaTotalAmount());
            everydayCost.setIaaDividendAmount(dateDTO.getIaaDividendAmount());
            everydayCost.setIaaRegisterTotalAmount(dateDTO.getIaaRegisterTotalAmount());
            everydayCost.setIaaRegisterDividendAmount(dateDTO.getIaaRegisterDividendAmount());
            everydayCost.setIaaDividendAmountSw(dateDTO.getIaaDividendAmountSw());
            everydayCost.setIaaRegisterDividendAmountSw(dateDTO.getIaaRegisterDividendAmountSw());
            everydayCost.computeProfitAmount();
            everydayCost.computeRateValue();
            if (isAdd) {
                this.save(everydayCost);
            } else {
                this.updateById(everydayCost);
            }
        }

        List<OceEverydayCostHours> addHoursList = new ArrayList<>();
        List<OceEverydayCostHours> updateHoursList = new ArrayList<>();
        List<OceEverydayCostHours> hoursList = oceEverydayCostHoursMapper.selectJobList(new LambdaQueryWrapper<OceEverydayCostHours>().eq(OceEverydayCostHours::getReferralLinkId, iaaReq.getReferralLinkId())
            .eq(OceEverydayCostHours::getThatdayTimestamp, dateDTO.getThatdayTimestamp()));

        for (Map.Entry<Long, IaaOrderAmountHoursDTO> hoursEntry : iaaReq.getHoursMap().entrySet()) {
            if (dateDTO.getThatdayTimestamp().longValue() != hoursEntry.getValue().getThatdayTimestamp().longValue()) {
                log.info("校正日期不等于小时中的日期，跳过更新时速");
                continue;
            }
            BigDecimal dividendAmount = OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getIaaTotalAmount());
            hoursEntry.getValue().setIaaDividendAmount(dividendAmount);
            BigDecimal iaaDividendAmount = OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getIaaRegisterTotalAmount());
            hoursEntry.getValue().setIaaRegisterDividendAmount(iaaDividendAmount);

            BigDecimal dividendAmountSw = OceEverydayCostHours.computeIaaDividendAmountSw(referralLinkType, appType, hoursEntry.getValue().getIaaTotalAmount());
            hoursEntry.getValue().setIaaDividendAmountSw(dividendAmountSw);
            BigDecimal iaaDividendAmountSw = OceEverydayCostHours.computeIaaDividendAmountSw(referralLinkType, appType, hoursEntry.getValue().getIaaRegisterTotalAmount());
            hoursEntry.getValue().setIaaRegisterDividendAmountSw(iaaDividendAmountSw);

            hoursEntry.getValue().setDividendAmountHoursCurrent(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursCurrent()));
            hoursEntry.getValue().setDividendAmountHoursOne(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursOne()));
            hoursEntry.getValue().setDividendAmountHoursTwo(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursTwo()));
            hoursEntry.getValue().setDividendAmountHoursThree(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursThree()));
            hoursEntry.getValue().setDividendAmountHoursFour(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFour()));
            hoursEntry.getValue().setDividendAmountHoursFive(OceEverydayCostHours.computeIaaDividendAmount(referralLinkType, appType, hoursEntry.getValue().getAmountHoursFive()));

            IaaOrderAmountHoursDTO hoursDTO = hoursEntry.getValue();
            OceEverydayCostHours hoursCost = null;
            Optional<OceEverydayCostHours> first = hoursList.stream().filter(item -> item.getThatdayHoursTimestamp().longValue() == hoursDTO.getThatdayHoursTimestamp().longValue()).findFirst();
            boolean isHoursAdd = false;
            if (first.isEmpty()) {
                isHoursAdd = true;
                hoursCost = new OceEverydayCostHours();
                BeanUtil.copyProperties(relation, hoursCost);
                hoursCost.setThatdayTimestamp(hoursDTO.getThatdayTimestamp());
                hoursCost.setThatdayDate(DateTimeUtil.getStrDate(hoursDTO.getThatdayTimestamp()));
                hoursCost.setThatdayHoursTimestamp(hoursDTO.getThatdayHoursTimestamp());
                hoursCost.setThatdayHoursDate(TimeUtils.getStrHoursDate(hoursDTO.getThatdayHoursTimestamp()));
            } else {
                hoursCost = first.get();
            }
            hoursCost.setIaaTotalAmount(hoursDTO.getIaaTotalAmount());
            hoursCost.setIaaDividendAmount(hoursDTO.getIaaDividendAmount());
            hoursCost.setIaaRegisterTotalAmount(hoursDTO.getIaaRegisterTotalAmount());
            hoursCost.setIaaRegisterDividendAmount(hoursDTO.getIaaRegisterDividendAmount());
            hoursCost.computeProfitAmount();
            hoursCost.computeRateValue();

            hoursCost.setDividendAmountHoursCurrent(hoursDTO.getDividendAmountHoursCurrent());
            hoursCost.setDividendAmountHoursOne(hoursDTO.getDividendAmountHoursOne());
            hoursCost.setDividendAmountHoursTwo(hoursDTO.getDividendAmountHoursTwo());
            hoursCost.setDividendAmountHoursThree(hoursDTO.getDividendAmountHoursThree());
            hoursCost.setDividendAmountHoursFour(hoursDTO.getDividendAmountHoursFour());
            hoursCost.setDividendAmountHoursFive(hoursDTO.getDividendAmountHoursFive());

            if (isHoursAdd) {
                addHoursList.add(hoursCost);
            } else {
                updateHoursList.add(hoursCost);
            }
        }
        oceEverydayCostHoursService.saveBatch(addHoursList);
        oceEverydayCostHoursService.updateBatchById(updateHoursList);

        return iaaReq.getReferralLinkId();
    }

}
